
package com.gcloud.mesh.dcs.dao;

import java.util.ArrayList;
import java.util.List;

import javax.validation.Valid;

import org.springframework.stereotype.Repository;

import com.gcloud.framework.db.PageResult;
import com.gcloud.framework.db.dao.impl.JdbcBaseDaoImpl;
import com.gcloud.mesh.dcs.entity.SchedulerAdviceEntity;
import com.gcloud.mesh.header.msg.dcs.PageSchedulerAdviceMsg;
import com.gcloud.mesh.header.vo.dcs.SchedulerAdviceVo;

@Repository
public class SchedulerAdviceDao extends JdbcBaseDaoImpl<SchedulerAdviceEntity, Long> {

	public PageResult<SchedulerAdviceVo> page(@Valid PageSchedulerAdviceMsg msg) {
		List<Object> values = new ArrayList<>();

		StringBuilder sb = new StringBuilder();
		sb.append("SELECT d.* FROM dcs_scheduler_advice d  WHERE 1=1 ");

		if (msg.getName() != null) {
			sb.append(" AND d.app_name LIKE concat('%', ?, '%')");
			values.add(msg.getName());
		}
		if (msg.getDatacenterId() != null) {
			sb.append(" AND d.src_datacenter_id = ? ");
			values.add(msg.getDatacenterId());
		} 
		if(msg.getModelType() != null) {
			sb.append(" AND d.scheduler_model = ? ");
			values.add(msg.getModelType());
		}
		sb.append(" AND d.status = 0 ");
		sb.append(" ORDER BY if(isnull(d.create_time),0,1),d.create_time desc,d.app_id DESC");
		
		return this.findBySql(sb.toString(), values, msg.getPageNo(), msg.getPageSize(), SchedulerAdviceVo.class);
	}

	public void deleteByAppId(String appId) {
		StringBuffer buff = new StringBuffer();
		buff.append(" delete from dcs_scheduler_advice where app_id =  ");
		String appIdStr = "'"+appId+"'";
		buff.append(appIdStr);
		jdbcTemplate.execute(buff.toString());
		
	}

	public void deleteByInstanceId(String instanceId) {
		StringBuffer buff = new StringBuffer();
		buff.append(" delete from dcs_scheduler_advice where instance_id =  ");
		String instanceIdStr = "'"+instanceId+"'";
		buff.append(instanceIdStr);
		jdbcTemplate.execute(buff.toString());
		
	}

	public void deleteByReadyStatus(int model) {
		StringBuffer buffer = new StringBuffer();
		// buffer.append(" delete from dcs_scheduler_advice where status = 0 ");
		buffer.append("delete from dcs_scheduler_advice where app_id not in (select b.app_id from (select app_id from dcs_scheduler_advice where `status` = 3) b)"); 
		buffer.append(" and scheduler_model =  ? ");
		jdbcTemplate.update(buffer.toString(), model);
	}
	
	public void updateStatusByInstanceId(int status, String instanceId) {
		StringBuffer buffer = new StringBuffer();
		buffer.append(" update dcs_scheduler_advice set status = ? where instance_id = ? ");
		jdbcTemplate.update(buffer.toString(), status, instanceId);
	}


}
